package com.tanhua.server.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.UsersApi;
import com.tanhua.dubbo.server.pojo.Comment;
import com.tanhua.dubbo.server.pojo.PageInfo;
import com.tanhua.dubbo.server.pojo.Users;
import com.tanhua.server.pojo.Announcement;
import com.tanhua.server.pojo.User;
import com.tanhua.server.pojo.UserInfo;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.Contacts;
import com.tanhua.server.vo.MessageAnnouncement;
import com.tanhua.server.vo.MessageLike;
import com.tanhua.server.vo.PageResult;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * @description:
 * @author: Administrator
 * @date: Created in 2021/2/23 21:25
 * @version: 0.0.1
 * @modified By:
 */
@Service
public class IMService {

    @Reference(version = "1.0.0")
    private UsersApi usersApi;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private UserInfoService userInfoService;

    @Value("${tanhua.sso.url}")
    private String ssoUrl;

    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    @Autowired
    private AnnouncementService announcementService;

    public Boolean contactUser(Long userId) {
        //添加好友到MongoDB
        User user = UserThreadLocal.get();
        Users users = new Users();
        users.setUserId(user.getId());
        users.setFriendId(userId);
        this.usersApi.saveUsers(users);
        //注册好友关系到环信
        String url = ssoUrl + "/user/huanxin/contacts/" + user.getId() + "/" + userId;
        ResponseEntity<Void> responseEntity = this.restTemplate.postForEntity(url, null, Void.class);
        if (responseEntity.getStatusCodeValue() == 200) {
            return true;
        }
        return false;
    }

    public PageResult queryContactsList(Integer page, Integer pageSize, String keyword) {
        User user = UserThreadLocal.get();
        List<Users>usersList=null;
        if(StringUtils.isEmpty(keyword)){
            //关键字为空，进行分页查询
            PageInfo<Users> pageInfo = this.usersApi.queryUsersList(user.getId(), page, pageSize);
            usersList=pageInfo.getRecords();
        }else{
            //关键字不为空，查询所有的好友，在后面进行关键字过滤
           usersList=this.usersApi.queryAllUsersList(user.getId());
        }
        List<Long> userIds = new ArrayList<>();
        for (Users users : usersList) {
            if (!userIds.contains(users.getFriendId())) {
                userIds.add(users.getFriendId());
            }
        }
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);
        if(StringUtils.isNotEmpty(keyword)){
            queryWrapper.like("nick_name",keyword);
        }
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(queryWrapper);
        List<Contacts> contactsList = new ArrayList<>();
        if(StringUtils.isEmpty(keyword)){
            for (Users users : usersList) {
                for (UserInfo userInfo : userInfoList) {
                    if(users.getFriendId().longValue()==userInfo.getId().longValue()){
                        Contacts contacts = new Contacts();
                        contacts.setAge(userInfo.getAge());
                        contacts.setAvatar(userInfo.getLogo());
                        contacts.setGender(userInfo.getSex().name().toLowerCase());
                        contacts.setNickname(userInfo.getNickName());
                        contacts.setUserId(String.valueOf(userInfo.getUserId()));
                        contacts.setCity(StringUtils.substringBefore(userInfo.getCity(), "-"));
                        contactsList.add(contacts);
                        break;
                    }
                }
            }
        }else{
            //填充用户信息
            for (UserInfo userInfo : userInfoList) {
                Contacts contacts = new Contacts();
                contacts.setAge(userInfo.getAge());
                contacts.setAvatar(userInfo.getLogo());
                contacts.setGender(userInfo.getSex().name().toLowerCase());
                contacts.setNickname(userInfo.getNickName());
                contacts.setUserId(String.valueOf(userInfo.getUserId()));
                contacts.setCity(StringUtils.substringBefore(userInfo.getCity(), "-"));
                contactsList.add(contacts);
            }
        }
        PageResult pageResult = new PageResult();
        pageResult.setPages(0);
        pageResult.setCounts(0);
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        pageResult.setItems(contactsList);
        return pageResult;
    }

    public PageResult queryMessageLikeList(Integer page, Integer pageSize) {
        return queryMessageList(page,pageSize,1);
    }

    public PageResult queryMessageCommentList(Integer page, Integer pageSize) {
        return queryMessageList(page,pageSize,2);
    }

    public PageResult queryMessageLoveList(Integer page, Integer pageSize) {
        return queryMessageList(page,pageSize,3);
    }

    private PageResult queryMessageList(Integer page, Integer pageSize,Integer type){
        User user=UserThreadLocal.get();
        PageResult pageResult=new PageResult();
        pageResult.setPages(0);
        pageResult.setCounts(0);
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        PageInfo<Comment> pageInfo = this.quanZiApi.queryCommentListByUser(user.getId(), type, page, pageSize);
        List<Comment> records = pageInfo.getRecords();
        List<Long>userIds=new ArrayList<>();
        for (Comment record : records) {
            if(!userIds.contains(record.getUserId())){
                userIds.add(record.getUserId());
            }
        }
        QueryWrapper<UserInfo>queryWrapper=new QueryWrapper<>();
        queryWrapper.in("user_id",userIds);
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(queryWrapper);
        List<MessageLike>messageCommentList=new ArrayList<>();
        for (Comment record : records) {
            for (UserInfo userInfo : userInfoList) {
                if(record.getUserId().longValue()==userInfo.getUserId().longValue()){
                    MessageLike messageLike=new MessageLike();
                    messageLike.setId(record.getId().toHexString());
                    messageLike.setCreateDate(new DateTime(record.getCreated()).toString("yyyy-MM-dd HH:mm"));
                    messageLike.setAvatar(userInfo.getLogo());
                    messageLike.setNickname(userInfo.getNickName());
                    messageCommentList.add(messageLike);
                    break;
                }
            }
        }
        pageResult.setItems(messageCommentList);
        return pageResult;
    }
    /**
     * @description
     * @author
     * @date
     * @param 公告
     *@return
     */
    public PageResult queryMessageAnnouncementList(Integer page, Integer pageSize) {
        PageResult pageResult=new PageResult();
        pageResult.setPages(0);
        pageResult.setCounts(0);
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        IPage<Announcement> announcementIPage = this.announcementService.queryList(page, pageSize);
        List<Announcement> records = announcementIPage.getRecords();
        List<MessageAnnouncement>messageAnnouncementList=new ArrayList<>();
        for (Announcement record : records) {
            MessageAnnouncement messageAnnouncement=new MessageAnnouncement();
            messageAnnouncement.setId(record.getId().toString());
            messageAnnouncement.setCreateDate(new DateTime(record.getCreated()).toString("yyyy-MM-dd HH:mm"));
            messageAnnouncement.setDescription(record.getDescription());
            messageAnnouncement.setTitle(record.getTitle());
            messageAnnouncementList.add(messageAnnouncement);
        }
        pageResult.setItems(messageAnnouncementList);
        return pageResult;
    }
}
